<template>
  <div class="web-chat">
    <el-row :gutter="30">
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>在线用户(点击聊天气泡开始聊天)</span>
            </div>
          </template>
          <el-scrollbar height="400px">
            <div
              class="user-cls"
              v-for="user in userList"
              :key="user.username"
              @click="selectChatUser(user)"
            >
              {{ user.username }}
              <div class="chat">
                <el-icon size="20">
                  <svg-icon name="chat" />
                </el-icon>
                <span
                  v-if="chatUser.username"
                  style="display: inline-block; color: #09d96e"
                  >正在聊天中...</span
                >
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
      <el-col :span="15">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span
                >Web聊天室<span v-if="chatUser.username"
                  >({{ chatUser.username }})</span
                ></span
              >
            </div>
          </template>
          <div>
            <div
              class="pd-cls message-box"
              v-html="content"
              id="message_box"
            ></div>
            <div>
              <el-input
                v-model="message"
                placeholder="请输入聊天消息"
                type="textarea"
                rows="2"
                id="textarea_id"
              />
            </div>
            <div class="pd-cls text-right">
              <el-button type="primary" @click="sendMsg">发送</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  name: "webchat",
};
</script>
<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { getServerUrl, getWsBaseUrl } from "@/utils/request.js";
import { useStore } from "vuex";
import load from "@/utils/load.js"; // 引入

const store = useStore();
const message = ref(""); //发送的消息
const messageList = ref([]); //服务端发送的消息列表
const userList = ref([]); //用户列表
const content = ref(""); //消息信息(html)
const chatUser = ref(""); //聊天对象
const user = ref({}); //
let socket = null;

const createContent = (remoteUser, nowUser, text) => {
  let html = "";
  if (nowUser) {
    html = `<div style="text-align:right;
      width:100%;
      padding-right:10px;
      box-sizing: border-box;
      line-height:25px;
      font-size:12px;
      display:flex;
      align-items: center;
      justify-content: flex-end;
      margin-bottom:10px;
      ">
      <div style="
      background: ${store.state.themeColor};
      position: relative;
      border-radius: 4px;
      max-width: calc(100% - 60px)
      box-sizing: border-box;
      padding:8px;
      margin-right:10px;
      color:white
      ">
      ${text}
      <div style="
        position: absolute;
        right: -8px;
        top: 50%;
        width: 0;
        height: 0;
        border-top: 9px solid transparent;
        border-right: none;
        border-left: 8px solid ${store.state.themeColor};
        border-bottom: 9px solid transparent;
        transform: translateY(-50%);
      "
      ></div>
      </div>
      <img
            style="border-radius:50%"
            width="40px"
            src="${getServerUrl()}image/userAvatar/${nowUser.avatar}"
            alt=""
          />
    </div>`;
  } else {
    html = `<div style="
         width:100%;
        padding-left:10px;
        box-sizing: border-box;
        line-height:25px;
        font-size:12px;
        display:flex;
        align-items: center;
        margin-bottom:10px;
      ">
         <img
            width="40px"
             style="border-radius:50%"
            src="${getServerUrl()}image/userAvatar/${remoteUser.avatar}"
            alt=""
          />
    
            <div
                style="background: #09D96E;
                position: relative;
                border-radius: 4px;
                max-width: calc(100% - 60px);
                box-sizing: border-box;
                padding:8px;
                margin-left:10px;
                color:white;"
              >
               ${text}
            <div style="
                  position: absolute;
                  right: 100%;
                  top: 50%;
                  width: 0;
                  height: 0;
                  border-top: 9px solid transparent;
                  border-right: 8px solid #09D96E;
                  border-bottom: 9px solid transparent;
                  transform: translateY(-50%);
                "
                ></div>
              </div>
      </div>`;
  }
  content.value += html;
  nextTick(() => {
    const message_box = document.getElementById("message_box");
    message_box.scrollTop = message_box.scrollHeight;
  });
};
const selectChatUser = (user) => {
  chatUser.value = user;
};

const sendMsg = () => {
  if (!chatUser.value) {
    ElMessage({
      type: "warning",
      message: "聊天对象不能为空",
    });
    return;
  }
  if (!message.value) {
    ElMessage({
      type: "warning",
      message: "发送消息不能为空",
    });
    return;
  } else {
    if (typeof WebSocket == "undefined") {
      console.log("您的浏览器支持websocket");
    } else {
      let messageObj = {
        from: user.value.username,
        to: chatUser.value.username,
        text: message.value,
        avatar: user.value.avatar,
      };
      socket.send(JSON.stringify(messageObj));
      messageList.value.push({
        user: user.value.username,
        text: message.value,
        avatar: user.value.avatar,
      });
      createContent(null, user.value, message.value);
      message.value = "";
    }
  }
};
let socketUrl = "";
const init = () => {
  load.show()
  user.value = sessionStorage.getItem("currentUser")
    ? JSON.parse(sessionStorage.getItem("currentUser"))
    : {};
  if (typeof WebSocket == "undefined") {
    ElMessage({
      type: "error",
      message: "您的浏览器不支持websocket",
    });
  } else {
    socketUrl = getWsBaseUrl() + user.value.username;
    if (socket != null) {
      socket.close();
      socket = null;
    }
    socket = new WebSocket(socketUrl);
    //打开消息事件
    socket.onopen = () => {
      load.hide()
      console.log("websocket已经打开");
    };
    //获取消息事件
    socket.onmessage = (msg) => {
      console.log("收到数据====", msg.data);
      let data = JSON.parse(msg.data);
      console.log("data", data.users);
      if (data.users) {
        userList.value = data.users.filter(
          (item) => item.username !== user.value.username
        );
      } else {
        if (data.from === chatUser.value.username) {
          messageList.value.push(data);
          //构建消息内容
          createContent(data, null, data.text);
        }
      }
    };
    //关闭事件
    socket.onclose = () => {
      load.hide()
      console.log("websocket已关闭");
      setTimeout(function () {
        // 重新建立 WebSocket 连接
        socket = new WebSocket(socketUrl);
      }, 5000); // 5 秒后重新连接
    };
    //发生了错误
    socket.onerror = () => {
      load.hide()
      console.log("websocket发生了错误");
      // 自动重连
      setTimeout(function () {
        // 重新建立 WebSocket 连接
        socket = new WebSocket(socketUrl);
      }, 5000); // 5 秒后重新连接
    };
  }
};
init();
</script>
<style lang="less">
.web-chat {
  .el-textarea__inner {
    border-radius: 0;
    border-top: 0 none;
  }
}
</style>
<style lang="less" scoped>
.web-chat {
  width: 100%;
  overflow: hidden;
  padding: 10px;
  box-sizing: border-box;
  .pd-cls {
    padding: 20px 0;
  }
  .message-box {
    border: 1px solid #dcdfe6;
    border-bottom: none;
    height: 200px;
    overflow-y: auto;
  }
  .text-right {
    text-align: right;
    button {
      width: 120px;
    }
  }
  .user-cls {
    line-height: 25px;
    cursor: pointer;
    display: flex;
    align-items: center;
    font-size: 13px;
    .chat {
      margin-left: 2px;
      display: flex;
      align-content: center;
    }
  }
}
</style>